import time from 'locutus/php/datetime/time';

const {action} = jinghuan.props;

/**
 * 车型
 */
class carmodels extends jinghuan.AdminController {
    
    /**
     *
     * @return {QueryBuilder}
     * @private
     */
    _listModel(id = 0) {
        let model = this.db('jh_car_models as a')
            .leftJoin('jh_carscategory as b', 'b.id', 'a.carscategory_id')
            .leftJoin('jh_car_brand as c', 'c.id', 'a.brand_id')
            .select('a.*', 'b.name as carscategory', 'c.name as brand')
            .where('a.status', '>', 0);
        
        if (id) {
            model.where('a.id', id).first()
        }
        
        return model;
    }
    
    /**
     *
     */
    @action()
    async datatable() {
        let model1 = this._listModel();
        
        let model2 = this.db('jh_car_models as a')
            .count('a.id as count');
        
        await this.default_datatable2(model1, model2, [])
    }
    
    /**
     *
     * @return {Promise<void>}
     */
    @action({auth: false})
    async get_carmodels() {
        let data = await this.db('jh_car_models')
            .select('id as value', 'name as title', 'carscategory_id as group')
        
        this.callback(data);
    }
    
    /**
     *
     * @param name
     * @param code
     * @param brand_id
     * @param carscategory_id
     * @return {Promise<void>}
     */
    @action()
    async do_add({}, {name, code, brand_id, carscategory_id}) {
        let model = await this.db('jh_car_models')
            .insert({
                name,
                code,
                time: time(),
                u_time: time(),
                brand_id,
                carscategory_id
            });
        if (model) {
            this.record('添加车型成功');
            let data = await this._listModel(model[0]);
            this.callback(data, {toast: "message.success.add"});
        } else {
            this.record('添加车型失败');
            this.callback(false, {toast: "message.error.add"});
        }
    }
    
    /**
     *
     * @param GET
     * @param name
     * @param code
     * @param id
     * @param brand_id
     * @param carscategory_id
     * @return {Promise<void>}
     */
    @action({auth: false})
    async do_edit(GET, {name, code, id, brand_id, carscategory_id}) {
        let model = await this.db('jh_car_models')
            .where({id})
            .update({
                name,
                code,
                u_time: time(),
                brand_id,
                carscategory_id
            });
        
        if (model) {
            this.record('编辑车型成功');
            let data = await this._listModel(id);
            this.callback(data, {toast: "message.success.edit"});
        } else {
            this.record('编辑车型失败');
            this.callback(false, {toast: "message.error.edit"});
        }
        
    }
    
}

export default carmodels;
